<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="">
        <el-breadcrumb-item>
          <div class="div1">客户管理</div>
        </el-breadcrumb-item>
        <!-- <el-breadcrumb-item
          v-if="$route.query.isChange == 1"
          :to="{ path: '/myCustomers' }"
        >
          <div class="div3">我的客户</div>
        </el-breadcrumb-item> -->

        <el-breadcrumb-item
          v-if="$route.query.isTab == 2"
          :to="{
            name: 'customerInformation',
            query: { id: $route.query.id, navName: $route.query.isChange },
          }"
        >
          <div class="div3">客户资料</div>
        </el-breadcrumb-item>

        <el-breadcrumb-item
          v-if="$route.query.isTab == 1"
          :to="{
            name: 'reviewOrder',
            query: {
              customerId: this.id,
              taskId: this.taskId,
              orderId: this.orderId,
              total: this.total,
              receivedMoney: this.receivedMoney,
              channelOrderId:this.channelOrderId
            },
          }"
        >
          <div class="div3">订单审核</div>
        </el-breadcrumb-item>

        <el-breadcrumb-item
          v-if="isChange == 1 && $route.query.isTab != 2"
          :to="{
            name: 'fixOrder',
            query: {
              customerId: this.id,
              taskId: this.taskId,
              orderId: this.orderId,
              total: this.total,
              receivedMoney: this.receivedMoney,
              userIntention: this.$route.query.userIntention,
              userDitch: this.$route.query.userDitch,
              channelOrderId:this.channelOrderId
            },
          }"
        >
          <div class="div3">修改订单</div>
        </el-breadcrumb-item>

        <el-breadcrumb-item>
          <div class="div2">收货地址</div>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 面包屑导航 -->
    <!-- 添加并使用收货地址 -->
    <div class="btns">
      <el-button type="primary" size="mini" @click="addressHiddenEvent(0)"
        >新增地址</el-button
      >
    </div>
    <!-- <ul class="list">
      <li style="box-shadow: 0px 0px 5px 0 #ccc">
        <p class="header">添加收货地址</p>
        <el-form ref="address" :model="address" label-width="100px">
          <div class="select">
            <el-form-item label="收货人姓名">
              <el-input
                v-model="address.name"
                placeholder="请输入收货人姓名"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input
                v-model="address.phone"
                placeholder="请输入收货人电话"
              ></el-input>
            </el-form-item>
            <el-form-item label="收货地址">
              <levelAddr
                class="addressContent"
                :province="address.province"
                :city="address.city"
                :area="address.area"
                @updateprovice="getProvince"
                @updatecity="getCity"
                @updatearea="getArea"
              ></levelAddr>
            </el-form-item>
          </div>

          <div class="select1">
            <el-form-item label="详细地址">
              <el-input
                v-model="address.detail"
                @blur="getAddObj"
                @keydown.enter.native="getAddObj"
                placeholder="请输入收货详细地址"
              ></el-input>
            </el-form-item>
            <el-button
              type="primary"
              @click="add_addresss()"
              v-if="
                parArrayOpen.indexOf('customeraddressAddOpen') != -1 ||
                parArrayAssign.indexOf('customeraddressAddAssign') != -1 ||
                parArrayMy.indexOf('customeraddressAdd') != -1
              "
              >添加收货地址</el-button
            >
          </div>
        </el-form>
      </li>
    </ul> -->
    <!-- 添加并使用收货地址 -->
    <!-- 已有的地址列表 -->
    <!-- <ul class="list" v-if="list.length > 0">
      <li v-for="(items, index) in list" :key="items.id">
        <p class="header" v-if="items.isDefault == 0">收货地址</p>
        <p class="header" v-if="items.isDefault == 1">
          收货地址<span style="color: #ff0000; font-size: 14px"
            >(默认地址)</span
          >
        </p>
        <el-form label-width="100px">
          <div class="select">
            <el-form-item label="收货人姓名">
              <el-input
                v-model="items.userName"
                placeholder="请输入收货人姓名"
              ></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input
                v-model="items.phone"
                placeholder="请输入收货人电话"
              ></el-input>
            </el-form-item>
            <el-form-item label="收货地址">
              <levelAddr
                class="addressContent"
                :province="items.provinceCode"
                :city="items.cityCode"
                :area="items.regionCode"
                :adds="items"
              ></levelAddr>
            </el-form-item>
          </div>

          <div class="select1">
            <el-form-item label="详细地址">
              <el-input
                v-model="items.detailedAddress"
                placeholder="请输入收货详细地址"
                @blur="getAddObjT(items)"
                @keydown.enter.native="getAddObjT(items)"
              ></el-input>
            </el-form-item>
            <el-button
              type="primary"
              @click="editSussess(items)"
              v-if="
                parArrayOpen.indexOf('customeraddressUpdateOpen') != -1 ||
                parArrayAssign.indexOf('customeraddressUpdateAssign') != -1 ||
                parArrayMy.indexOf('customeraddressUpdate') != -1
              "
              >保存</el-button
            >
            <el-button
              type="primary"
              @click="useAddress(items)"
              v-if="
                parArrayOpen.indexOf('customeraddressUpdateAddressOpen') !=
                  -1 ||
                parArrayAssign.indexOf('fpkhsyshdz') != -1 ||
                parArrayMy.indexOf('customeraddressUpdateAddress') != -1
              "
              >使用收货地址</el-button
            >
            <el-button
              type="primary"
              v-if="
                (items.isDefault == 0 &&
                  parArrayOpen.indexOf('customeraddressIsTopOpen') != -1) ||
                (items.isDefault == 0 &&
                  parArrayAssign.indexOf('customeraddressIsTopAssign') != -1) ||
                (items.isDefault == 0 &&
                  parArrayMy.indexOf('customeraddressIsTop') != -1)
              "
              @click="setdefault(items.id)"
              >设为默认地址</el-button
            >-->
    <!-- 1为默认 -->
    <!-- <el-button
              type="primary"
              @click="delect(items.id, index)"
              v-if="
                parArrayOpen.indexOf('customeraddressDeleteOpen') != -1 ||
                parArrayAssign.indexOf('customeraddressDeleteAssign') != -1 ||
                parArrayMy.indexOf('customeraddressDelete') != -1
              "
              >删除收货地址</el-button
            >
          </div>
        </el-form>
      </li>
    </ul> -->
    <div class="table">
      <el-table
        :data="list"
        style="width: 100%"
        :cell-style="{ padding: '8px' }"
      >
        <el-table-column label="序号" width="80" type="index"></el-table-column>
        <el-table-column
          prop="userName"
          label="收货人"
          width="150px"
        ></el-table-column>
        <el-table-column
          width="150px"
          prop="phone"
          label="联系电话"
        ></el-table-column>
        <el-table-column label="省/市/区">
          <template slot-scope="scope">
            {{ scope.row.provinceCode }}/{{ scope.row.cityCode }}/{{
              scope.row.regionCode
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="detailedAddress"
          label="详细地址"
        ></el-table-column>
        <el-table-column label="设置默认收货地址" width="150px">
          <template slot-scope="scope">
            <el-radio
              @change="setdefault(scope.row.id)"
              v-model="radio"
              :label="scope.row.id"
              >默认收货地址</el-radio
            >
          </template>
        </el-table-column>
        <el-table-column prop="noticeTitle" label="操作" width="140px">
          <template slot-scope="scope">
            <p class="opeation" @click="addressHiddenEvent(scope.row)">编辑</p>
            <p class="opeation" @click="delect(scope.row.id, scope.$index)">
              删除
            </p>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 地址编辑弹框 -->
    <el-dialog
      :visible.sync="addressHidden"
      :append-to-body="true"
      :title="ifNews == 0 ? '新增地址' : '编辑地址'"
    >
      <el-form
        ref="address"
        label-position="right"
        :model="address"
        label-width="100px"
      >
        <el-form-item label="收货人姓名">
          <el-input
          maxlength="128"
            v-model="address.name"
            placeholder="请输入客户姓名"
          ></el-input>
        </el-form-item>

        <el-form-item label="联系电话">
          <el-input
          maxlength="128"
            v-model="address.phone"
            placeholder="请输入收货电话"
          ></el-input>
        </el-form-item>

        <el-form-item label="收货地址">
          <levelAddr
            class="addressContent"
            :province="address.province"
            :city="address.city"
            :area="address.area"
            @updateprovice="getProvince"
            @updatecity="getCity"
            @updatearea="getArea"
          ></levelAddr>
        </el-form-item>

        <el-form-item label="详细地址">
          <el-input
          maxlength="128"
            class="address"
            v-model="address.detail"
            @blur="getAddObj"
            @keydown.enter.native="getAddObj"
            placeholder="请输入客户详细地址"
          ></el-input>
        </el-form-item>
        <div>
          <el-form-item v-if="ifNews == 1">
            <el-checkbox
              :true-label="1"
              :false-label="0"
              v-model="address.isDefault"
              >默认收获地址</el-checkbox
            >
            <!-- @change="setdefault" -->
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          v-if="ifNews == 1"
          size="mini"
          type="primary"
          @click="editSussess()"
          >确 定</el-button
        >

        <el-button
          v-if="ifNews == 0"
          size="mini"
          type="primary"
          @click="
            add_addresss();
          "
          >确 定</el-button
        >

        <el-button size="mini" @click="addressHidden = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 地址编辑弹框 -->
  </div>
</template>

<script>
import levelAddr from "@/components/levelAddr";
import $ from "jquery";
export default {
  components: {
    levelAddr,
  },
  data() {
    return {
      radio: 1,
      addressHidden: false,
      ifNews: 0,
      address: {
        name: "",
        phone: "",
        province: "",
        city: "",
        area: "",
        detail: "",
        isDefault: 1,
        addressId: "",
      },
      id: "",
      list: [],
      isChange: "", //判断是否从修改订单进来
      customerId: "",
      taskId: "",
      orderId: "",
      total: "",
      receivedMoney: "",
      limits: "",
      channelOrderId:"",
      parArrayOpen: [], //公开客户
      parArrayAssign: [],
      parArrayMy: [],
    };
  },
  created() {
    // 权限设定判断
    this.limits = JSON.parse(sessionStorage.getItem("limit"));

    const params = this.limits.buttonTreeDto.filter(
      (item) => item.menuCode === "openCustomersCode"
    );
    if (params.length) {
      params[0].buttonList.forEach((item) => {
        this.parArrayOpen.push(item.code);
      });
    }
    // 分配客户
    const paramsAssign = this.limits.buttonTreeDto.filter(
      (item) => item.menuCode === "assignCustomCode"
    );
    if (paramsAssign.length) {
      paramsAssign[0].buttonList.forEach((item) => {
        this.parArrayAssign.push(item.code);
      });
    }

    // 我的客户
    const paramsMy = this.limits.buttonTreeDto.filter(
      (item) => item.menuCode === "myCustomersCode"
    );
    if (paramsMy.length) {
      paramsMy[0].buttonList.forEach((item) => {
        this.parArrayMy.push(item.code);
      });
    }
    // 权限设定判断
    this.id = this.$route.query.id; //客户id
    this.taskId = this.$route.query.taskId;
    this.total = this.$route.query.total;
    this.isChange = this.$route.query.isChange;
    if(this.$route.query.channelOrderId){
      this.channelOrderId = this.$route.query.channelOrderId;
    }

    this.orderId = this.$route.query.orderId;
    this.receivedMoney = this.$route.query.receivedMoney;
    this.listAxios();
  },
  methods: {
    getAddObj() {
      this.address.detail = this.address.detail.replaceAll(" ", "");
      $.get(
        "http://120.24.147.235:3002/test",
        { addr: this.address.detail },
        (res) => {
          let addrObj = res.message;
          debugger
          if (
            this.address.detail.indexOf(
              addrObj.province + addrObj.city + addrObj.county
            ) === 0
          ) {
            this.updateAddr(addrObj);
          } else {
            var t = 0;
            this.address.detail.indexOf(addrObj.province) === 0 ? t++ : (t = t);
            this.address.detail.indexOf(addrObj.city) != -1 ? t++ : (t = t);
            this.address.detail.indexOf(addrObj.county) != -1 ? t++ : (t = t);
            if (t >= 2) {
              this.updateAddr(addrObj);
            }
          }
        }
      );
    },
    updateAddr(e) {
      this.address.province = e.province;
      this.address.city = e.city;
      this.address.area = e.county;
      this.address.detail = this.address.detail.replace(
        this.address.province,
        ""
      );
      this.address.detail = this.address.detail.replace(this.address.city, "");
      this.address.detail = this.address.detail.replace(this.address.area, "");
    },

    getAddObjT(e) {
      e.detailedAddress = e.detailedAddress.replaceAll(" ", "");
      $.get(
        "http://120.24.147.235:3002/test",
        { addr: e.detailedAddress },
        (res) => {
          let addrObj = res.message;
          if (
            e.detailedAddress.indexOf(
              addrObj.province + addrObj.city + addrObj.county
            ) === 0
          ) {
            this.updateAddrT(e, addrObj);
          } else {
            var t = 0;
            e.detailedAddress.indexOf(addrObj.province) === 0 ? t++ : (t = t);
            e.detailedAddress.indexOf(addrObj.city) != -1 ? t++ : (t = t);
            e.detailedAddress.indexOf(addrObj.county) != -1 ? t++ : (t = t);
            if (t >= 2) {
              this.updateAddrT(e, addrObj);
            }
          }
        }
      );
    },
    updateAddrT(e1, e2) {
      e1.provinceCode = e2.province;
      e1.cityCode = e2.city;
      e1.regionCode = e2.county;
      e1.detailedAddress = e1.detailedAddress.replace(e1.provinceCode, "");
      e1.detailedAddress = e1.detailedAddress.replace(e1.cityCode, "");
      e1.detailedAddress = e1.detailedAddress.replace(e1.regionCode, "");
    },
    /**地址列表数据请求**/
    listAxios() {
      this.axios
        .get("/order/comm/customeraddress/list?id=" + this.id, {
          headers: {
            isLoading: true,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.list = res.data;
            let flag = false;
            for (let i in this.list) {
              if (this.list[i].isDefault == 1) {
                this.radio = this.list[i].id;
                flag = true;
              }
            }
            if(!flag){
              this.radio = null;
            }
          }
        });
    },
    /**地址列表数据请求**/

    addressHiddenEvent(row) {
      this.addressHidden = true;
      if (row == 0) {
        this.address = {
          name: "",
          phone: "",
          province: "",
          city: "",
          area: "",
          detail: "",
          addressId: "",
          isDefault: 0,
        };
        this.ifNews = 0;
      } else {
        this.ifNews = 1;
        this.address = {
          name: row.userName,
          phone: row.phone,
          province: row.provinceCode,
          city: row.cityCode,
          area: row.regionCode,
          detail: row.detailedAddress,
          addressId: row.id,
          isDefault: row.isDefault,
        };
      }
    },
    /**添加地址**/
    add_addresss: _.debounce(function () {
      if (this.address.name == "") {
        this.$message.warning("收货人未填");
      } else if (
        this.address.phone == "" ||
        !this.judgeIsNum(this.address.phone)
      ) {
        this.$message.warning("联系电话有误");
      } else if (this.address.province == "" || this.address.city == "") {
        this.$message.warning("省-市-区未填");
      } else if (this.address.detail == "") {
        this.$message.warning("详细地址未填");
      } else {
        this.axios
          .post(
            "/order/comm/customeraddress/add",
            {
              address:
                this.address.province + this.address.city + this.address.area,
              cityCode: this.address.city,
              createdBy: sessionStorage.getItem("user_id"),
              customerId: "",
              detailedAddress: this.address.detail,
              id: "",
              isDefault: this.address.isDefault,
              phone: this.address.phone,
              provinceCode: this.address.province,
              regionCode: this.address.area,
              userName: this.address.name,
              userId: this.id,
            },
            {
              headers: {
                isLoading: false,
              },
            }
          )
          .then((res) => {
            // console.log(res);
            if (res.code == 0) {
              this.listAxios();
              this.addressHidden = false
              this.address = {
                name: "",
                phone: "",
                province: "",
                city: "",
                area: "",
                detail: "",
                isDefault: "",
              };
              this.$message.success("添加成功");
            } else {
              this.$message.error(res.message);
            }
          });
      }
    }, 300),
    /**添加地址**/

    getProvince(val) {
      this.address.province = val;
      this.address.city = "";
      this.address.area = "";
    },
    getCity(val) {
      this.address.city = val;
      this.address.area = "";
    },
    getArea(val) {
      this.address.area = val;
    },
    /**设置默认地址**/
    setdefault(id) {
      this.axios
        .get("/order/comm/customeraddress/isTop?id=" + id, {
          headers: {
            isLoading: false,
          },
        })
        .then((res) => {
          if (res.code == 0) {
            this.$message.success("设置成功");
            this.listAxios();
          } else {
            this.$message.error(res.message);
          }
        });
    },
    /**设置默认地址**/
    /**使用地址**/
    useAddress(row) {
      this.axios
        .get(
          "/order/comm/customeraddress/updateAddress?addressId=" +
            row.id +
            "&userId=" +
            this.id,
          {
            headers: {
              isLoading: false,
            },
          }
        )
        .then((res) => {
          // console.log(res)
          if (res.code == 0) {
            this.editSussess(row);
            if (this.is_null(this.isChange)) {
              this.$message.success("使用成功");
              // this.$router.push({name:"add_order",query:{addressId:row.id,customerId:this.id,orderId:this.orderId,total:this.total}});
            } else if (this.isChange == 1) {
              this.$router.push({
                name: "fixOrder",
                query: {
                  addressId: row.id,
                  customerId: this.id,
                  taskId: this.taskId,
                  orderId: this.orderId,
                  total: this.total,
                  receivedMoney: this.receivedMoney,
                  isChange: this.isChange,
                  jage: this.$route.query.jage,
                  userIntention: this.$route.query.userIntention,
                  userDitch: this.$route.query.userDitch,
                  channelOrderId:this.channelOrderId,
                },
              });
            } else if (this.isChange == 2) {
              this.$router.push({
                name: "reviewOrder",
                query: {
                  addressId: row.id,
                  customerId: this.id,
                  taskId: this.taskId,
                  orderId: this.orderId,
                  total: this.total,
                  receivedMoney: this.receivedMoney,
                  userIntention: this.$route.query.userIntention,
                  userDitch: this.$route.query.userDitch,
                },
              });
            }
          } else {
            this.$message.error(res.message);
          }
        });
    },
    // 保存修改地址
    editSussess: _.debounce(function () {
      if (this.address.name == "") {
        this.$message.warning("收货人未填");
      } else if (this.address.phone == "") {
        this.$message.warning("联系电话未填");
      } else if (
        this.address.province == "" ||
        this.address.city == "" ||
        this.address.province == null ||
        this.address.city == null
      ) {
        this.$message.warning("省-市未填");
      } else if (this.address.detail == "") {
        this.$message.warning("详细地址未填");
      } else {
        this.addressHidden = false;
        this.axios
          .post(
            "/order/comm/customeraddress/update",
            {
              address:
                this.address.province + this.address.city + this.address.area,
              cityCode: this.address.city,
              createdBy: sessionStorage.getItem("user_id"),
              customerId: "",
              detailedAddress: this.address.detail,
              id: this.address.addressId,
              isDefault: this.address.isDefault,
              phone: this.address.phone,
              provinceCode: this.address.province,
              regionCode: this.address.area,
              userName: this.address.name,
              userId: this.id,
            },
            {
              headers: {
                isLoading: false,
              },
            }
          )
          .then((res) => {
            // console.log(res);
            if (res.code == 0) {
              this.listAxios();
              this.$message.success("修改成功");
            } else {
              this.$message.error(res.message);
            }
          });
      }
    }, 300),
    /**使用地址**/
    /** 删除地址 **/
    delect: _.debounce(function (id, index) {
      this.$confirm("确定要删除该地址吗, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.axios
            .get(
              "/order/comm/customeraddress/delete?addressId=" +
                id +
                "&userId=" +
                this.id,
              {
                headers: {
                  isLoading: false,
                },
              }
            )
            .then((res) => {
              // console.log(res)
              if (res.code == 0) {
                this.list.splice(index, 1);
                // this.listAxios();
                this.$message.success("删除成功");
              } else {
                this.$message.error(res.message);
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    }, 300),
    /** 删除地址 **/
    is_null(content) {
      if (content) {
        return false;
      } else {
        return true;
      }
    },
  },
};
</script>

<style scoped lang="scss">
.div1 {
  margin-left: -16px;
  background: url(../../assets/breadcrumb2.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}

.div2 {
  margin-left: -16px;
  background: url(../../assets/breadcrumb1.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #fff;
}

.div3 {
  margin-left: -8px;
  background: url(../../assets/breadcrumb3.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
/deep/.el-table th > .cell {
  color: #333;
}
.list {
  li {
    margin-bottom: 20px;
    background: #fff;
    padding: 10px;
  }

  .header {
    font-size: 16px;
    color: #2d7edf;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }

  .select {
    margin-top: 20px;

    .el-form-item {
      display: inline-block;
    }
  }

  /deep/.el-input__inner {
    width: 200px;
    height: 30px;
    line-height: 30px;
  }

  /deep/.distpicker-address-wrapper select {
    padding: 0rem 0.75rem;
    height: 30px;
    line-height: 30px;
    font-size: 15px;
  }
}

.select1 {
  .el-form-item {
    display: inline-block;
  }

  /deep/.el-input__inner {
    width: 300px;
  }
}
.btns {
  margin-bottom: 10px;
}

.opeation {
  display: inline-block;
  padding: 0 10px;
  color: #2d7edf;
}
.opeation:hover {
  cursor: pointer;
}
</style>
